package org.example.system.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.LoginLog;
import org.example.system.entity.OperateLog;
import org.example.system.entity.User;
import org.example.system.service.LoginLogService;
import org.example.system.service.OperateLogService;
import org.example.system.service.UserService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制层
 */
@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private OperateLogService operateLogService;

    //操作日志对象
    private OperateLog operateLog = new OperateLog("用户管理");

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User loginUser, HttpServletRequest request) throws Exception {
        //登录日志对象
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(loginUser.getUsername());

        log.info("--------AuthController | login | input:{}", JSON.toJSONString(loginUser));
        if (StrUtil.isEmpty(loginUser.getUsername()) ||
                StrUtil.isEmpty(loginUser.getPassword())){
            loginLog.setStatus("失败");
            loginLog.setInfo("参数错误");
            loginLogService.add(loginLog,request);
            return R.fail("参数错误");
        }
        //判断验证码是否正确
        String key = "LOGIN_VALID_CODE:" + loginUser.getClientUid();
        String code = (String)redisTemplate.opsForValue().get(key);
        if (!loginUser.getValidcode().equals(code)){
            loginLog.setStatus("失败");
            loginLog.setInfo("验证码错误");
            loginLogService.add(loginLog,request);
            return R.fail("验证码错误");
        }
        Object token = userService.login(loginUser);
        loginLog.setStatus("成功");
        loginLog.setInfo("登录成功");
        loginLogService.add(loginLog,request);
        return R.ok(token);
    }

    /**
     * 按条件分页查询
     * @param user
     * @return
     */
    @GetMapping("/list")
    public R list(User user){
        IPage<User> page = userService.selectPage(user);
        log.info("------------ UserController | list | selectPage | return : {} ", JSON.toJSONString(page));
        return R.ok(page);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody User user,HttpServletRequest request){
        operateLog.setUsername(user.getCreateBy());
        log.info("--------- UserController | add | input : {}", JSON.toJSON(user));
        int row = userService.add(user);
        if(row <= 0){
            operateLog.setInfo("添加失败");
            operateLogService.add(operateLog,request);
            return R.fail("添加失败");
        }
        operateLog.setInfo("添加成功");
        operateLogService.add(operateLog,request);
        return R.ok("添加成功");
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody User user,HttpServletRequest request){
        operateLog.setUsername(user.getUpdateBy());
        log.info("--------- UserController | update | input : {}", JSON.toJSON(user));
        if(null == user.getId() || user.getId() <= 0){
            operateLog.setInfo("参数错误:ID未传入");
            operateLogService.add(operateLog,request);
            return R.fail("参数错误:ID未传入");
        }
        int row = userService.update(user);
        if(row <= 0){
            operateLog.setInfo("修改失败");
            operateLogService.add(operateLog,request);
            return  R.fail("修改失败");
        }
        operateLog.setInfo("修改成功");
        operateLogService.add(operateLog,request);
        return R.ok("修改成功");
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PutMapping("/updatePassword")
    public R updatePassword(@RequestBody User user,HttpServletRequest request){
        operateLog.setUsername(user.getUpdateBy());
        log.info("--------- UserController | update | input : {}", JSON.toJSON(user));
        if(null == user.getId() || user.getId() <= 0){
            operateLog.setInfo("参数错误:ID未传入");
            operateLogService.add(operateLog,request);
            return R.fail("参数错误:ID未传入");
        }
        //根据ID查询用户，用户存在比对传入参数的旧密码与数据库中用户的密码是否相同
        User exitUser = userService.getOne(user.getId());
        int row = -1;
        if (exitUser != null && DigestUtil.bcryptCheck(user.getOldPassword(),exitUser.getPassword())){
            row = userService.update(user);
        }
        if(row <= 0){
            operateLog.setInfo("修改密码失败");
            operateLogService.add(operateLog,request);
            return R.fail("修改密码失败");
        }
        operateLog.setInfo("修改密码成功");
        operateLogService.add(operateLog,request);
        return R.ok("修改密码成功");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping( "/delete")
    public R delete(Long[] ids,String sender,HttpServletRequest request){
        operateLog.setUsername(sender);
        log.info("--------- UserController | delete | input : {}", JSON.toJSON(ids));
        int row = userService.deleteBatch(ids);
        if(row <= 0){
            operateLog.setInfo("删除失败");
            operateLogService.add(operateLog,request);
            return R.fail("删除失败");
        }
        operateLog.setInfo("删除成功");
        operateLogService.add(operateLog,request);
        return R.ok("删除成功");
    }

    /**
     * 根据id查询用户数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getInfo(@PathVariable("id") Long id){
        log.info("--------- UserController | getInfo | input : {}", JSON.toJSON(id));
        return R.ok(userService.getOne(id));
    }

    /**
     * 根据username查询用户数据
     * @param username
     * @return
     */
    @GetMapping("/select")
    public R getInfo(String username){
        log.info("--------- UserController | getInfo | input : {}", JSON.toJSON(username));
        return R.ok(userService.getOne(username));
    }
}
